import {defineStore} from "pinia";
import type {RouteRecordRaw} from "vue-router";
import {MENU_ROUTE_NAME, routes} from "@/router";

type PermissionState = {
    routes: Array<RouteRecordRaw>;
};

const filterRoutes = (
    routes: Array<RouteRecordRaw>,
    permissions: Array<string>
) => {
    return routes.filter((route: RouteRecordRaw) => {

        if (route.children) {
            //console.log("有children信息的")
            route.children = filterRoutes(route.children, permissions);
        }
        // 1. 没有定义meta的路由 ： !route.meta
        // 2. 没有定义meta里面permission !route.meta.permission
        // 3. permission是否存在与当前permissions 里面
        return (
            !route.meta ||
            (route.meta &&
                (!route.meta.permission ||
                    (route.meta.permission &&
                        permissions.includes(route.meta.permission))))
        );
        /*if(!route.meta || !route.meta.permission) {
            console.log("没有meta信息")
            return true;
        }else if( permissions.includes(route.meta.permission) ){
            console.log("包含在permissions的")
            return true;
        }
        return false;*/
    });
};

// 所有的NameList 平铺到数组
const buildPermissionRoutesNameList = (routes: Array<RouteRecordRaw>) => {
    const nameList: Array<RouteRecordName> = [];
    routes.forEach((route) => {
        if (route.children) {
            nameList.push(...buildPermissionRoutesNameList(route.children));
        }
        if (route.name) {
            nameList.push(route.name);
        }
    });
    return nameList;
};

export const usePermissionStore = defineStore("permission", {
    state: (): PermissionState => {
        return {
            routes: [],
        };
    },
    persist: {
        storage: sessionStorage, // localStorage 或 sessionStorage
        key: 'permission', // 自定义Storage存储的名称
    },
    actions: {
        generateRoutes(permissions: Array<string>, admin = false) {
            /*console.log("打印筛选后的permissions");
            console.log(permissions[0]);*/
            this.routes = admin ? routes : filterRoutes(routes, permissions);
            /*console.log("打印筛选后的routes");
            console.log(routes);*/
        },
    },
    getters: {
        menuRoutes(): Array<RouteRecordRaw> | undefined {
            return this.routes.find(
                (route: RouteRecordRaw) => route.name === MENU_ROUTE_NAME
            )?.children;
        },

        // 做403页面时候方便获取
        permissionRouteNamesList(): Array<RouteRecordName> {
            return this.routes ? buildPermissionRoutesNameList(this.routes) : [];
        },
    },
});